const mysql = require('mysql');
const {
	$UL_API_LOG,
	$UL_SQL_LOG,
} = require('../../logger/logger')
const options = require('../../config/mysqlConf.json')
const {
	getMSTime,
} = require('../../utils/dateUtils')

const connection = mysql.createConnection(options);

connection.connect();

module.exports = {

	selectOne(params) {
		return parseOptions(params, 'query', 0)
	},

	select(params) {
		return parseOptions(params, 'query')
	},

	insert(params) {
		return parseOptions(params, 'add')
	},

	insertBatch(params) {
		return parseOptions(params, 'batch')
	},

	update(params) {
		return parseOptions(params, 'update')
	},

	remove(params) {
		return parseOptions(params, 'delete')
	},

	executeSQL(SQL) {
		return dbConnection(SQL)
	},
}

function parseOptions(options, type, idx) {
	if (typeof options == 'string') {
		return dbConnection(options, idx)
	}
	let {
		table,
		fields = [],
		updates = [],
		values = [],
		where = [],
		batch = [],
		condition = '',
	} = options
	fields = fields.map((val, idx) => {
		return val.replace(/[`'"\\\/]/g, '')
	})
	fields = fields.join(',')
	updates = updates.join(',')
	values = values.map((val, idx) => {
		if (val == 'NOW()')
			return val
		if (/^[A-Z]+\([\s\S]+\)/.test(val))
			return val
		if (typeof val == 'string' && !/^'[\S\s]*'$/.test(val))
			return `'${val}'`
		return val
	})
	values = values.join(',')
	batch = batch.join(',')
	where.unshift('1 = 1')
	where = where.join(' AND ')
	let SQL = ''
	if (type == 'query')
		SQL = `SELECT ${fields} FROM ${table} WHERE ${where} ${condition};`
	else if (type == 'add')
		SQL = `INSERT INTO ${table} (${fields}) VALUES (${values});`
	else if (type == 'update')
		SQL = `UPDATE ${table} SET ${updates} WHERE ${where};`;
	else if (type == 'batch')
		SQL = `INSERT INTO ${table} (${fields}) VALUES ${batch};`
	else if (type == 'delete')
		SQL = `DELETE FROM ${table} WHERE ${where};`;
	return dbConnection(SQL, idx)
}

function dbConnection(SQL, idx) {
	// 记录SQL日志
	$UL_SQL_LOG(`${getMSTime()} ===>>> ${SQL}`);
	return new Promise((resolve, reject) => {
		connection.query(SQL, (error, results, fields) => {
			if (error) {
				$UL_API_LOG(SQL, 'error');
				return reject(error);
			}
			let rstr = JSON.stringify(results)
			if (rstr.length < 1000)
				$UL_API_LOG(`返回结果: ${rstr}`);
			// return resolve({
			// 	results,
			// 	fields,
			// })
			if (typeof idx == 'number' && idx >= 0) {
				results = results[idx]
			}
			return resolve(results);
		});
	})
}